package com.phz.springcloud.study.service;

import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.phz.springcloud.study.vo.CreditScoreResponse;

/**
 * 消息订阅者
 * 
 * @author penghaozhong
 *
 */
@Component
@RabbitListener(queues = "score-queue")
public class ScoreReceiver {

	protected static final Logger logger = LoggerFactory.getLogger(ScoreReceiver.class);

	private static final ObjectMapper mapper = new ObjectMapper();
	
	private static final int SIZE = 5;
	private LinkedBlockingQueue<CreditScoreResponse> socreResponseQueue = new LinkedBlockingQueue<>(SIZE);

	/**
	 * 监控策略
	 * 统计20个连续的查询结果
	 * 如果状态码全是2(暂无手机号) 则可能是运营商上月数据没有更新，则请查询时间调整到上上月
	 * @param scoreJson
	 */
	@RabbitHandler
	private void process(String scoreJson){
		CreditScoreResponse score;
		try {
			logger.info("==============score"+scoreJson);
			score = mapper.readValue(scoreJson, CreditScoreResponse.class);
			if (score != null) {
				socreResponseQueue.put(score);
				// 如果队列满了则进行监控
				if(socreResponseQueue.remainingCapacity() == 0 ) {
					if(socreResponseQueue.stream().filter(s -> s.getCode() == 2).count() == SIZE) {
						logger.info("185异常了，把查询时间切换至上上月");
						socreResponseQueue.take();
						return;
					}
					
					if(socreResponseQueue.stream().filter(s -> s.getCode() == 1302).count() == SIZE) {
						logger.info("服务错误，请记录错误查询，后面让客户重查");
						socreResponseQueue.take();
						return;
					}
					
					System.out.println("数据正常");
					socreResponseQueue.take();
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
